/*
 *  Copyright 2012 Anton Van Zyl. http://code.google.com/p/java-swiss-knife/
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package com.knife.version;

import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;


/**
 * This is a utility class containing methods helping with version algorithms.
 * <code>xx.xx.xx.xxxx</code> is a normal version pattern, but this can handle
 * different patterns easily.
 * 
 * <br/>
 * <br/>
 * Please visit <a
 * href="http://code.google.com/p/java-swiss-knife/">Java-Swiss-Knife</a> and
 * comment, rate, contribute or raise a issue/enhancement for my library. <br/>
 * 
 * @author Anton Van Zyl
 * 
 */
public final class VersionUtil {

	/**
	 * This will compare two input versions.
	 * <ul>
	 * <li>Unknown - The input is not expected input</li>
	 * <li>LowerVersion - Your Version is lower than the needed version</li>
	 * <li>EqualVersion - The two versions is equal to each other</li>
	 * <li>HigherVersion - You have a higher version than the needed version</li>
	 * </ul>
	 * 
	 * @param neededVersion - The version that you need it to be.
	 * @param yourVersion - The version that serves as input you need to check.
	 * @return Compare
	 */
	public static Compare compare(String neededVersion, String yourVersion) {
		if (StringUtils.isNotEmpty(neededVersion) && StringUtils.isNotEmpty(yourVersion)) {
			String s1 = normalisedVersion(yourVersion);
			String s2 = normalisedVersion(neededVersion);
			int cmp = s1.compareTo(s2);
			if (cmp < 0) {
				return Compare.LowerVersion;
			} else if (cmp > 0) {
				return Compare.HigherVersion;
			} else if (cmp == 0) {
				return Compare.EqualVersion;
			}
		}
		return Compare.Unknown;
	}

	private static String normalisedVersion(String version) {
		return normalisedVersion(version, ".", 4);
	}

	private static String normalisedVersion(String version, String sep, int maxWidth) {
		String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
		StringBuilder sb = new StringBuilder();
		for (String s : split) {
			sb.append(String.format("%" + maxWidth + 's', s));
		}
		return sb.toString();
	}
}